package com.tt.pay.ali

import android.app.Activity
import android.content.Context
import android.os.Handler
import android.text.TextUtils
import com.alipay.sdk.app.PayTask
import com.tt.pay.impl.IPay
import com.tt.pay.PayResultCallBack
import java.lang.ref.WeakReference

/**
 * Created by  tengtao 2019-11-21 11:40
 * @Description:
 */
class AliPay : IPay<String> {

    companion object {
        const val ERROR_RESULT = 1   //支付结果解析错误
        const val ERROR_PAY = 2  //支付失败
    }

    private var mPayTask: PayTask? = null

    private var activity: WeakReference<Activity>? = null
    private var handler: Handler? = null


    override fun doPay(context: Context, params: String, callBack: PayResultCallBack?) {
        activity = WeakReference(context as Activity)
        mPayTask = PayTask(activity!!.get())
        handler = Handler()
        Thread(Runnable {
            val payResult = mPayTask!!.payV2(params, true)
            handler?.post(Runnable {
                if (callBack == null) {
                    return@Runnable
                }

                if (payResult == null) {
                    callBack.onError(ERROR_RESULT)
                    return@Runnable
                }

                val resultStatus = payResult!!.get("resultStatus")!!
                when {
                    TextUtils.equals(resultStatus, "9000") -> //支付成功
                        callBack.onSuccess()
                    TextUtils.equals(resultStatus, "6001") -> //支付取消
                        callBack.onCancel()
                    else -> callBack.onError(ERROR_PAY, thirdErrorCode = resultStatus)
                }
            })
        }).start()
    }

    override fun release() {
        activity?.clear()
        activity = null
        handler?.removeCallbacksAndMessages(null)
        mPayTask = null
    }
}